"""
存储桶管理 API
"""
from fastapi import Depends, Path

from axiom_boot.api.models import (
    PaginatedResponse, success_response, ApiResponse, PaginationParams
)
from axiom_boot.di import controller, autowired
from axiom_boot.auth.permission import pre_authorize
from axiom_boot.api.controller import BaseController, get, post, put, delete
from axiom_boot.core.exceptions import BadRequest

from src.storage.service.storage_bucket_service import StorageBucketService
from src.storage.models.api_models import (
    BucketVO, BucketCreateDTO, BucketUpdateDTO, BucketFilterParams
)


@controller("/storage/buckets", tags=["存储桶管理"])
class StorageBucketController(BaseController):
    """
    提供存储桶的增删改查接口
    """

    def __init__(self, bucket_service: StorageBucketService = autowired()):
        self.bucket_service = bucket_service

    @post(
        "",
        summary="新增存储桶",
        response_model=ApiResponse[BucketVO]
    )
    async def create_bucket(
        self,
        bucket_dto: BucketCreateDTO
    ) -> ApiResponse[BucketVO]:
        new_bucket = await self.bucket_service.create_bucket(bucket_dto)
        return success_response(
            data=BucketVO.model_validate(new_bucket),
            message="存储桶创建成功"
        )

    @get(
        "",
        summary="获取存储桶列表（分页）",
        response_model=ApiResponse[PaginatedResponse[BucketVO]]
    )
    async def get_bucket_list(
        self,
        pagination: PaginationParams = Depends(),
        filters: BucketFilterParams = Depends()
    ) -> ApiResponse[PaginatedResponse[BucketVO]]:
        
        filter_dict = filters.to_filter_dict()

        paginated_db_buckets = await self.bucket_service.page(
            pagination=pagination,
            filters=filter_dict,
            order_by=filters.order_by
        )
        
        vo_items = [BucketVO.model_validate(item) for item in paginated_db_buckets.items]
        
        paginated_vo_response = PaginatedResponse[BucketVO](
            items=vo_items,
            total=paginated_db_buckets.total,
            page=paginated_db_buckets.page,
            page_size=paginated_db_buckets.page_size
        )
        return success_response(data=paginated_vo_response)

    @delete(
        "/{bucket_id}",
        summary="删除存储桶",
        response_model=ApiResponse,
        status_code=200
    )
    async def remove_bucket(
        self,
        bucket_id: str = Path(..., description="要删除的存储桶ID"),
    ) -> ApiResponse:
        await self.bucket_service.delete_bucket(int(bucket_id))
        return success_response(message="存储桶删除成功")

    @get(
        "/{bucket_id}",
        summary="获取存储桶详情",
        response_model=ApiResponse[BucketVO]
    )
    async def retrieve_bucket_details(
        self,
        bucket_id: str = Path(..., description="要查询的存储桶ID"),
    ) -> ApiResponse[BucketVO]:
        bucket = await self.bucket_service.find_by_pk_or_fail(int(bucket_id))
        return success_response(data=BucketVO.model_validate(bucket))

    @put(
        "/{bucket_id}",
        summary="修改存储桶信息",
        response_model=ApiResponse[BucketVO]
    )
    async def update_bucket(
        self,
        bucket_dto: BucketUpdateDTO,
        bucket_id: str = Path(..., description="要修改的存储桶ID"),
    ) -> ApiResponse[BucketVO]:
        update_data = bucket_dto.model_dump(exclude_unset=True)
        if not update_data:
            raise BadRequest("至少需要提供一个待更新的字段")
            
        updated_bucket = await self.bucket_service.update_by_pk(int(bucket_id), update_data)
        return success_response(
            data=BucketVO.model_validate(updated_bucket),
            message="存储桶信息更新成功"
        )
